<?php
class Tool {

    public static function test() {
        echo('tetts');
    }
    public static function display($name){
        //$name='Home/'.$name;
        $session=Yii::$app->session;
        $userInfo=$session->get('userInfo');
        $auth = Yii::$app->authManager;
        if(!$auth -> checkAccess($userInfo['id'], $name)){
            echo ("style='display:none'");
        }
    }
    /*
     * 功能:是否有权限,有的话是true没有的是false
     */
    public static function isHaveAccess($name){
        //$name='Home/'.$name;
        $session=Yii::$app->session;
        $userInfo=$session->get('userInfo');
        $auth = Yii::$app->authManager;
        if(!$auth -> checkAccess($userInfo['id'], $name)){
            return false;
        }
        return true;
    }

    public static function array_column($input, $columnKey, $indexKey = NULL)
    {
        $columnKeyIsNumber = (is_numeric($columnKey)) ? TRUE : FALSE;
        $indexKeyIsNull = (is_null($indexKey)) ? TRUE : FALSE;
        $indexKeyIsNumber = (is_numeric($indexKey)) ? TRUE : FALSE;
        $result = array();
        foreach ((array)$input AS $key => $row)
        {
            if ($columnKeyIsNumber)
            {
                $tmp = array_slice($row, $columnKey, 1);
                $tmp = (is_array($tmp) && !empty($tmp)) ? current($tmp) : NULL;
            }
            else
            {
                $tmp = isset($row[$columnKey]) ? $row[$columnKey] : NULL;
            }
            if ( ! $indexKeyIsNull)
            {
                if ($indexKeyIsNumber)
                {
                    $key = array_slice($row, $indexKey, 1);
                    $key = (is_array($key) && ! empty($key)) ? current($key) : NULL;
                    $key = is_null($key) ? 0 : $key;
                }
                else
                {
                    $key = isset($row[$indexKey]) ? $row[$indexKey] : 0;
                }
            }
            $result[$key] = $tmp;
        }
        return $result;
    }

    //获得session值
    public static  function getsession_admin_id($id){
        $session = Yii::$app->session;
        $userInfo=$session->get('userInfo');
        return $userInfo[$id];
    }


    //获得cookie值
    public static  function getcookie_admin_id($id){
        $cookies = \Yii::$app->request->cookies;
        $userInfo=$cookies->getValue(backend\models\Login::COOKIE_KEY_USER);
        return $userInfo[$id];
    }
    /*
 * 获得 四位编号  年月日+4位流水  如：201607210001
 * */
    public static function get_bianhao1($id){
        $begin=date("Ymd",time());
        $bit = 4;//产生7位数的数字编号
        $num_len = strlen($id);
        $zero = '';
        for($i=$num_len; $i<$bit; $i++){
            $zero .= "0";
        }
        $real_num = $begin.$zero.$id;
        return  $real_num;
    }

    /*
 * 获得 四位编号
 * */
    public static function get_bianhao($begin,$num){
        $bit = 4;//产生7位数的数字编号
        $num_len = strlen($num);
        $zero = '';
        for($i=$num_len; $i<$bit; $i++){
            $zero .= "0";
        }
        $real_num = $begin.$zero.$num;
        return  $real_num;
    }

    /*
     * 计算几天后，几小时后，几分钟后，几周，几个月，几年后的时间？
     * $endtime=date('Y-m-dH:i:s',strtotime($endtime.'1month'));
     * $endtime=date('Y-m-dH:i:s',strtotime($endtime.'1week'));
     * $endtime=date('Y-m-dH:i:s',strtotime($endtime.'1day'));
     * $endtime=date('Y-m-dH:i:s',strtotime($endtime.'1year'));
     * $endtime=date('Y-m-dH:i:s',strtotime($endtime.'1hour'));
     * $endtime=date('Y-m-dH:i:s',strtotime($endtime.'1minute'));
     * */
    public static function get_month_time($begin_time,$count){
        $month=$count."month";
        $endtime=date('Y-m-d H:i:s',strtotime($begin_time.$month));
        return $endtime;
    }


    /*
    * 判断两个日期相差
    * 'year' => int 0
    * 'month' => int 3
    * 'day' => int 0
    * */
    public static function diffDate($date1,$date2){
        if(strtotime($date1)>strtotime($date2)){
            $tmp=$date2;
            $date2=$date1;
            $date1=$tmp;
        }
        list($Y1,$m1,$d1)=explode('-',$date1);
        list($Y2,$m2,$d2)=explode('-',$date2);
        $Y=$Y2-$Y1;
        $m=$m2-$m1;
        $d=$d2-$d1;
        if($d<0){
            $d+=(int)date('t',strtotime("-1 month $date2"));
            $m--;
        }
        if($m<0){
            $m+=12;
            $Y--;
        }
        return array('year'=>$Y,'month'=>$m,'day'=>$d);
    }

    public static function curl_post($url, $post_data){
        //var_dump($post_data); var_dump($url);

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);

        $output = curl_exec($ch);
        //$output = array('sms'=>'5703', 'status' => '03');
        curl_close($ch);
        //print_arr( json_decode( $output ) );die;
        return $output;
    }
    /**
     * 获取服务器端IP地址
     * @return string
     */

    public static function get_server_ip() {
        if (isset($_SERVER)) {
            if($_SERVER['SERVER_ADDR']) {
                $server_ip = $_SERVER['SERVER_ADDR'];
            } else {
                $server_ip = $_SERVER['LOCAL_ADDR'];
            }
        } else {
            $server_ip = getenv('SERVER_ADDR');
        }
        return $server_ip;
    }

    //活动开始时间
    // defined('BEGIN_SHARE_TIME') or define('BEGIN_SHARE_TIME', 1464166814);
    // define('BEGIN_SHARE_TIME', 1464166814);//活动开始时间
    // define('END_SHARE_TIME', 1465747200);//活动结束时间

    /**
     * 获取服务器端IP地址
     * @return string
     */

    //计算时间戳相差的时间
    public static function timediff($begin_time,$end_time)
    {
        if($begin_time < $end_time){
            $starttime = $begin_time;
            $endtime = $end_time;
        }else{
            $starttime = $end_time;
            $endtime = $begin_time;
        }

        //计算天数
        $timediff = $endtime-$starttime;
        $days = intval($timediff/86400);
        //计算小时数
        $remain = $timediff%86400;
        $hours = intval($remain/3600);
        //计算分钟数
        $remain = $remain%3600;
        $mins = intval($remain/60);
        //计算秒数
        $secs = $remain%60;
        if($days&&$hours&&$mins&&$secs){
            $time=$days."天".$hours."小时".$mins."分钟".$secs."秒";
        }elseif(empty($days)&&$hours&&$mins&&$secs){
            $time=$hours."小时".$mins."分钟".$secs."秒";
        }elseif(empty($days)&&empty($hours)&&$mins&&$secs){
            $time=$mins."分钟".$secs."秒";
        }elseif(empty($days)&&empty($hours)&&empty($mins)&&$secs){
            $time=$secs."秒";
        }else{
            $time="";
        }
        $res = $time;
        return $res;
    }


    //计算百分比
    public static function getbfl($a,$b){
        $bfl=round(($a/$b)*100,2).'%';
        return $bfl;
    }


    //小数 转化百分数
    public static function get_bfl_xs($num){
        $bfl=round($num*100,2).'%';
        return $bfl;
    }

    //小数 保留两位小数
    public static function get_two($num){
        $bfl=round($num,2);
        return $bfl;
    }

    /*
    * 两个时间 相差 多少天
    * */
    public static function diffBetweenTwoDays ($second1, $second2 ,$count)
    {
        if ($second1 < $second2) {
            $tmp = $second2;
            $second2 = $second1;
            $second1 = $tmp;
        }
        return intval(($second1 - $second2) / 86400/$count);
    }

    /*
     * 计算自然周
     * */
    public static function find_Week($begin_time){
        //$begin_time=date("Y-m-d H:i:s",$begin+_time);
        $end_time=strtotime('last sunday');
        $array=[];
        if($begin_time<$end_time){
            $week_count =Tool::diffBetweenTwoDays($begin_time,$end_time,7)+1;
            for($i=1;$i<=$week_count;$i++){
                $array[$i][]=date("Y-m-d H:i:s",mktime(0, 0 , 0,date("m"),date("d")-date("w")+1-7*$i,date("Y")));
                $array[$i][]=date("Y-m-d H:i:s",mktime(23,59,59,date("m"),date("d")-date("w")+7-7*$i,date("Y")));
            }
            return $array;
        }else{
            return $array;
        }

    }

    /*
     * 计算自然月
     * */
     public static function find_Month($begin_time){
        //$begin_time=date("Y-m-d H:i:s",$begin+_time);
        $end_time=mktime(23,59,59,date("m") ,0,date("Y"));
        $array=[];
        //$end_time=date("Y-m-d H:i:s",$end_time);
        if($begin_time<$end_time){
            $week_count = Tool::diffBetweenTwoDays($begin_time,$end_time,30)+1;
            //$array=\Tool::diffDate($begin_time,$end_time);

            for($i=0;$i<$week_count;$i++){
                $array[$i][]=date("Y-m-d H:i:s",mktime(0, 0 , 0,date("m")-1-$i,1,date("Y")));
                $array[$i][]=date("Y-m-d H:i:s",mktime(23,59,59,date("m") -$i,0,date("Y")));
            }
            return $array;
        }else{
            return $array;
        }

    }
    /*
     * 计算自然天
     * */
     public static function find_Day($begin_time){
        //结束时间
        $end_time = time();
        $week_count=Tool::diffBetweenTwoDays($begin_time,$end_time,1);
        $array=[];
        for($i=1;$i<=$week_count;$i++){
            $array[$i][]=date('Y-m-d', strtotime("-$i day"))." 00:00:00";
            $array[$i][]=date('Y-m-d', strtotime("-$i day"))." 23:59:59";
        }
        return $array;
    }
    /*
     * 根据 开始时间 和 类型 获得 可选时间数据
     *$begin_time  $circle_time   day,week,month
     * */

     public static function find_array_time($begin_time,$circle_time){
        switch($circle_time){
            case "day":
                $array_time = Tool::find_Day($begin_time);
                break;
            case "week":
                $array_time = Tool::find_Week($begin_time);
                break;
            case "month":
                $array_time = Tool::find_Month($begin_time);
                break;
            default:
        }
        return $array_time;
    }


    //数字和字符混搭的四位随机字符串：
    public static function GetRandStr($len,$type="ALL")
    {
        switch($type){
            case "SEN":
                $chars = array(
                    "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
                    "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
                    "w", "x", "y", "z"
                );
                break;
            case "BEN":
                $chars = array(
                    "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K",
                    "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",
                    "W", "X", "Y", "Z"
                );
                break;
            case "CN":
                $chars = array(
                    "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"
                );
                break;
            case "ALL":
                $chars = array(
                    "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
                    "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
                    "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",
                    "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
                    "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2",
                    "3", "4", "5", "6", "7", "8", "9"
                );
                break;
            default:

        }
        $charsLen = count($chars) - 1;
        shuffle($chars);
        $output = "";
        for ($i=0; $i<$len; $i++)
        {
            $output .= $chars[mt_rand(0, $charsLen)];
        }
        return $output;
    }

    //判断是否是生产服务器
    public static function is_sc_service($server_ip=""){
        if($server_ip==""){
            //获得服务器ip
            $server_ip=\Tool::get_server_ip();
        }
        //拼接url  www.yiduyongche.com
        if($server_ip=="123.57.229.136"){
            return true;
        }else{
            return false;
        }
    }

    /*
     * 导出 cvs 文件
     *fileName  缓存文件明 例:workorderlist
     *header  缓存文件头部 []
     * content  内容数组
     * fields  内容留下的字段
     * chfilename 下载文件生成的名字
     * */
    public static function export_cvs($data){
        $url=self::create_cvs(['fileName'=>$data['fileName'],'header'=>$data['header']]);
        self::addr_cvs(['url'=>$url,'fields'=>$data['fields'],'content'=>$data['content']]);
        self::download_cvs(['url'=>$url,'chfileName'=>$data['chfileName']]);
    }

    /*
     * 生成cvs [type=>'create','fileName'=>$fileName,header=>$header]
     * $fileName = "IbeaconWdlist";
     * $header = array('序号', '车牌号', '计费网点', '车辆归属网点', '驶入时间', '开始计费时间', '驶出时间', '结束计费时间', '状态', '有效性', '停车费类型', '费用（元）');
     * $fileName=\Tool::create_cvs(['type'=>'create','fileName'=>$fileName,'header'=>$header]);
     * */
    public static function create_cvs($data){
        if(is_array($data)&&isset($data['fileName'])&&$data['header']){
            $path       = \Yii::$app->basePath."/runtime";
            $prefix     = $data['fileName'].'csv_';
            $dir_name   = date('Ymd');//年月日命名文件夹 , 每天只是生成一个文件夹
            $full_dir_name  = $path.'/'.$prefix.$dir_name;
            // 步骤一 : 创建文件夹
            if(!file_exists($full_dir_name)){ //如果不存在,则新建文件夹
                mkdir($full_dir_name,0777);
            }
            $fileName = $full_dir_name. '/' .time().'.csv';
            // 标题数据
            $header = implode(',',$data['header']);
            $contents  = $header."\r\n";
            $contents = iconv("utf-8", "gb2312", $contents);//更改编码,防止乱码
            file_put_contents($fileName, $contents, FILE_APPEND);
            return $fileName;
        }else{
            return "参数不对应";
        }
    }

    /*
     * 给cvs 文件 追加内容
     * url 文件路径
     * content 数组内容
     * fields  数组中需要留下的字段
     * */
    public static function addr_cvs($data){
        $contents="";
        $contents_sum=[];
        if(is_array($data)&&$data['url']&&$data['fields']&&$data['content']){
            foreach($data['content'] as $k=>$v){
                foreach($data['fields'] as $key=>$val){
                    $contents_sum[$k][$val]=trim($data['content'][$k][$val])."\t";
                }
                if($contents_sum){
                    $contents .= implode(',',$contents_sum[$k]);
                    $contents .= "\r\n";
                }
            }
            if($data['content']){
                $contents = iconv("utf-8", "gbk", $contents);//更改编码,防止乱码
            }
            file_put_contents($data['url'], $contents, FILE_APPEND);
            unset($contents_sum);
            unset($contents);
            unset($data);
            return true;
        }else{
            return "参数不对应";
        }
    }

    /*
     * 下载cvs
     * url 文件路径
     * fileName 下载生成的文件名称
     * */
    public static function download_cvs($data){
        if(is_array($data)&&$data['url']&&$data['chfileName']){
            header("Content-Type: application/force-download");
            header("Content-Disposition: attachment; filename=".$data['chfileName'].'.csv');
            readfile($data['url']);
            exit;
        }else{
            return "参数不对应";
        }
    }

    /**
     * 删除图片或文件
     * @author Zhenwei Zhang <772979140@qq.com>
     * @param string $pic 图片或文件地址
     */

    public static function delpic($pic){
        if($pic){
            $url = strlen('http://'.$_SERVER['HTTP_HOST'].'/');
            $ifurl = strpos($pic,'upload');
            if($ifurl>10){
                if(file_exists(substr($pic, $url))){
                    $res = unlink(substr($pic, $url));
                    if($res){
                        $return = array('success'=>1,'errors'=>'删除图片或文件成功');
                        }else{
                        $return = array('success'=>0,'errors'=>'操作失误导致图片或文件无法删除');
                    }
                    }else{
                    $return = array('success'=>404,'errors'=>'无法找到文件或者已经删除');
                }
            }else{
                if(file_exists($pic)){
                    $res = unlink($pic);
                    if($res){
                        $return = array('success'=>1,'errors'=>'删除图片成功');
                    }else{
                        $return = array('success'=>0,'errors'=>'操作失误导致图片或文件无法删除');
                    }
                }else {
                    $return = array('success' => 404, 'errors' => '无法找到文件或者已经删除');
                }
            }
        }else{
            $return = array('success'=>404,'errors'=>'请传送正确图片或文件地址');
        }
        return $return;
    }


    /*
     * 获得当前页面uri
     * */
    public static function geturl(){
        return Yii::$app->request->getUrl();
    }

    //获得数组并集或者差集 city 或者 ittype  $type=true 差集 false
    public static function getarr($a="1,2",$b="2,3",$type=true){
        if(!is_array($a)){
            $a=explode(",",$a);
        }
        if(!is_array($b)){
            $b=explode(",",$b);
        }
        if($type){
            $res=array_intersect($a,$b);
        }else{
            $res=array_merge($a,$b);
        }
        return $res?implode(",",$res):"";
    }

}

?>